<template>
    <div class="chat-index">
        <el-row :gutter="0" class="chat-row">
            <el-col :span="8" class="chat-col">
                <div class="friend-list">
                    <ul class="list-ul">
                        <li>
                            <el-input v-model="searchTxt" placeholder="请输入内容" size="mini"></el-input>
                        </li>
                        <li v-for="(bean,idx) in friendList" :key="idx" @click="friendClick(idx)"
                            :class="{active:selectIndex==idx}">
                            <img src="../../assets/user-head.png" class="user-head"/>
                            <span class="offline" v-if="bean.status!=1"></span>
                            <div class="friend-right">
                                <span class="user-name">
                                   {{bean.name}}
                                    <span class="time right">{{bean.lastTime}}</span>
                                </span>
                                <span class="last-msg">
                                    <span class="msg-txt">{{bean.lastMsg}}</span>
                                    <span class="icon  right">
                                        <!--<i class="el-icon-bell"/>-->
                                        <template v-if="bean.unread>0">
                                            <span class="unread">{{bean.unread}}</span>
                                        </template>
                                    </span>
                                </span>
                            </div>
                        </li>
                    </ul>
                </div>
            </el-col>
            <el-col :span="16" class="chat-col">
                <div class="chat-content" v-if="selectIndex>=0">
                    <div class="friend-name">
                        {{friendList[selectIndex].name}}
                        <div class="inputting" v-if="inputting>0">输入中...</div>
                    </div>
                    <div class="msg-list" ref="msgList" v-loading="loading">
                        <div class="more" v-if="pageNo<totalPage"><a href="javascript:void(0)"
                                                                     @click="loadMore">加载更多</a></div>
                        <ul class="list-ul msg-ul">
                            <template v-for="(bean,idx) in messageList">
                                <li :key="idx" :class="{right:bean.fromUser==loginUser.userId}">
                                    <img src="../../assets/user-head.png" class="user-head"/>
                                    <div class="msg">
                                        <span class="msg-txt">{{bean.data}}</span>
                                    </div>
                                    <span class="msg-tip" v-if="bean.fromUser==loginUser.userId">{{bean.status===0?'未读':'已读'}}</span>
                                </li>
                            </template>
                        </ul>
                    </div>
                    <div class="send-input">
                        <textarea class="send-text" v-model="msg" @click="msgFocus" @keydown.enter.prevent="send">

                        </textarea>
                        <el-button size="small" @click="send" :disabled="!msg">发送</el-button>
                    </div>
                </div>
            </el-col>
        </el-row>
    </div>
</template>

<script>
    import Util from '../../components/Util';

    export default {
        name: 'ChatIndex',
        components: {},
        data() {
            return {
                searchTxt: '',
                selectIndex: -1,
                msg: '',
                friendList: [],
                messageList: [],
                loginUser: {},
                loading: false,
                pageNo: 1,
                totalPage: 1,
                inputting: 0,
                allList: [],
            }
        },
        watch: {
            searchTxt: {
                handler() {
                    let list = Util.Search(this.allList, 'name', this.searchTxt);
                    this.friendList = list;
                }
            }
        },
        methods: {
            getSocket() {
                return this.$store.state.socket;
            },
            loadFriendList(id) {
                this.$request(this.$api.friends, {}, (list) => {
                    let idx = -1;
                    for (let i = 0; i < list.length; i++) {
                        list[i].status = list[i].status || 0;
                        list[i].unread = list[i].unread || 0;
                        if (list[i].id === id) {
                            idx = i;
                        }
                    }
                    this.allList = list;
                    this.friendList = list;
                    this.friendClick(idx);
                })
            },
            scrollBottom() {
                this.$nextTick(() => {
                    try {
                        let content = this.$refs.msgList;
                        content.scrollTop = content.scrollHeight;
                    } catch (e) {
                        console.debug(e);
                    }
                })
            },
            loadMore() {
                let friendId = this.friendList[this.selectIndex].id;
                this.loading = true;
                this.pageNo = this.pageNo + 1;
                this.$request(this.$api.historyMsg, {friendId: friendId, pageNo: this.pageNo}, (page) => {
                    let list = page.list;
                    //发送已读消息
                    let ids = [];
                    list.forEach(item => {
                        //消息未读，并且接收人是我
                        if (item.status === 0 && item.toUser === this.loginUser.userId) {
                            ids.push(item.id);
                        }
                    })
                    if (ids.length > 0) {
                        this.getSocket().sendTo(this, this.loginUser.userId, this.friendList[this.selectIndex].id, JSON.stringify(ids), 'Read');
                    }
                    this.friendList[this.selectIndex].unread -= ids.length;
                    //拼接
                    let arr = [];
                    for (let i = 0; i < list.length; i++) {
                        arr.push(list[i]);
                    }
                    for (let i = 0; i < this.messageList.length; i++) {
                        arr.push(this.messageList[i]);
                    }
                    this.messageList = arr;

                    this.pageNo = page.pageNo;
                    this.totalPage = page.totalPage;
                    if (this.pageNo == 1)
                        this.scrollBottom();
                    this.loading = false;
                }, () => {
                    this.loading = false;
                });
            },
            friendClick(idx) {
                if (idx === this.selectIndex) {
                    return;
                }
                this.selectIndex = idx;
                this.pageNo = 0;
                this.totalPage = 0;
                this.messageList = [];
                this.loadMore();
            },
            msgFocus() {
                this.getSocket().sendTo(this, this.loginUser.userId, this.friendList[this.selectIndex].id, '', 'Input');
            },
            send() {
                if (!this.msg) {
                    return;
                }
                let data = this.getSocket().sendTo(this, this.loginUser.userId, this.friendList[this.selectIndex].id, this.msg, 'Send');
                this.msg = '';
            },
            addMsg(id, from, fromName, to, toName, msg, status) {
                //方向 dir  0 收到 1发送得      status 是否已读  0未读  1已读
                let data = {
                    id: id,
                    fromUser: from,
                    toUser: to,
                    data: msg,
                    status: status,
                    fromUserName: fromName,
                    toUserName: toName,
                    sendTime: '',
                    readTime: ''
                };
                if (to === this.loginUser.userId || from == this.loginUser.userId) {
                    this.messageList.push(data);
                }
                //如果是我收到得信息
                if (to === this.loginUser.userId) {
                    if (this.selectIndex >= 0 && this.friendList[this.selectIndex].id === from) {
                        this.friendList[this.selectIndex].lastMsg = msg;
                        this.getSocket().sendTo(this, this.loginUser.userId, from, JSON.stringify([id]), 'Read');
                    } else {
                        for (let i = 0; i < this.friendList.length; i++) {
                            if (this.friendList[i].id === from) {
                                this.friendList[i].lastMsg = msg;
                                this.friendList[i].unread++;  //如果是接收到并且当前选择用户不是这个用户的话 未读信息加一
                                break;
                            }
                        }
                    }
                }

                this.scrollBottom();
            },
            addOnline(userId, name) {
                let have = false;
                for (let i = 0; i < this.friendList.length; i++) {
                    if (this.friendList[i].id === userId) {
                        have = true;
                        break;
                    }
                }
                if (have == false) {
                    this.friendList.push({id: userId, name: name, head: '', unread: 0, status: 1})
                }
            },
            offline(name) {
                for (let i = 0; i < this.onlineList.length; i++) {
                    if (this.friendList[i].name === name) {
                        // this.selectIndex = -1;
                        // this.onlineList.splice(i, 1);
                        this.friendList[i].status = 2;  //离线
                        break;
                    }
                }
            },
            readMsg(userId, ids) {
                for (let i = 0; i < this.messageList.length; i++) {
                    let msg = this.messageList[i];
                    if (this.existArray(ids, msg.id)) {
                        msg.status = 1;  //已读
                    }
                }
            },
            existArray(array, id) {
                if (!array || array.length == 0) {
                    return false;
                }
                for (let i = 0; i < array.length; i++) {
                    if (array[i] === id) {
                        return true;
                    }
                }
                return false;
            },
            //事件监听
            receiveEvent(data) {
                this.addMsg(data.no, data.from, '', data.to, '', data.data, 0);
            },
            sendEvent(data) {
                this.addMsg(data.no, data.from, '', data.to, '', data.data, 0);
            },
            onlineEvent(data) {
                this.addOnline(data.from);
            },
            offLineEvent(data) {
                this.offline(data.from);
            },
            readEvent(data) {
                this.readMsg(data.from, JSON.parse(data.data));
            },
            inputEvent(data) {
                if (this.inputting < 2)
                    this.inputting++;
            },
            onlineListEvent(data) {
                let list = JSON.parse(data.data);
                list.forEach(item => {
                    this.addOnline(item);
                })
            },
            timerEvent() {
                if (this.inputting > 0)
                    this.inputting--;
            },
            clearEvent() {
                this.$event.off(this.$event.names.Receive, this.receiveEvent)
                this.$event.off(this.$event.names.Send, this.sendEvent)
                this.$event.off(this.$event.names.Online, this.onlineEvent)
                this.$event.off(this.$event.names.Offline, this.offLineEvent)
                this.$event.off(this.$event.names.Read, this.readEvent)
                this.$event.off(this.$event.names.Input, this.inputEvent)
                this.$event.off(this.$event.names.OnlineList, this.onlineListEvent)
                this.$event.off(this.$event.names.Timer, this.timerEvent)
            },
            addEvent() {
                this.$event.on(this.$event.names.Receive, this.receiveEvent)
                this.$event.on(this.$event.names.Send, this.sendEvent)
                this.$event.on(this.$event.names.Online, this.onlineEvent)
                this.$event.on(this.$event.names.Offline, this.offLineEvent)
                this.$event.on(this.$event.names.Read, this.readEvent)
                this.$event.on(this.$event.names.Input, this.inputEvent)
                this.$event.on(this.$event.names.OnlineList, this.onlineListEvent)
                this.$event.on(this.$event.names.Timer, this.timerEvent)
            },
        },
        created() {
            this.loginUser = this.$store.state.userInfo;
            this.clearEvent();
            this.addEvent();
            this.loadFriendList();
        },
        activated() {
            if (this.$route.params.id) {
                this.selectIndex = -1;
                this.loadFriendList(this.$route.params.id);
            }
        }

    }
</script>
<style lang="less" scoped>
    @import "../../assets/css/style.less";
</style>

